import React, { useState } from "react";
import { Calendar, Modal, Button, DatePicker ,Upload,Input,message,Form, InputNumber } from "antd";
import CustomSelect from './../../../components/CustomSelect/CustomSelect'
import UploadFile from './../../../components/UploadFile/UploadFile'
import "moment/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN";
import moment from "moment";
import Toolsbox from '@/components/Toolsbox'
import "./button.css";
import Http from '@/request'
import { CodeSandboxSquareFilled } from "@ant-design/icons";

const { Search } = Input;
const { RangePicker } = DatePicker
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const container = {
  width: "260px",
  border: "1px solid #f0f0f0",
  borderRadius: "2px",
  marginTop: "10px",
  marginLeft:'20px'
};
const calendarheader = {
  width: "100%",
  background: "#1890ff",
  padding: "5px 0",
  boxSizing: "border-box",
  color: "#fff",
  textAlign: "center",
  fontSize: "16px",
};
const calendarContainer = {
  display: "flex",
  width: "100%",
  flexWrap: "wrap",
  // justifyContent: "space-around",
};
class CalendarHeader extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <div style={calendarheader}>{this.props.date}</div>;
  }
}
const yearNow = new Date().getFullYear()
class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      height: window.innerHeight - 108,
      Mounths: [yearNow+'-'+1, yearNow+'-'+2, yearNow+'-'+3, yearNow+'-'+4, yearNow+'-'+5, yearNow+'-'+6, yearNow+'-'+7, yearNow+'-'+8, yearNow+'-'+9, yearNow+'-'+10, yearNow+'-'+11, yearNow+'-'+12],
      Mounths1: [yearNow+'-'+1, yearNow+'-'+2, yearNow+'-'+3, yearNow+'-'+4, yearNow+'-'+5, yearNow+'-'+6, yearNow+'-'+7, yearNow+'-'+8, yearNow+'-'+9, yearNow+'-'+10, yearNow+'-'+11, yearNow+'-'+12],
      selectedList: [],
      alldays: [],
      validateMessages : {
        required: '${label} is required!',
        types: {
          email: '${label} is not a valid email!',
          number: '${label} is not a valid number!',
        },
        number: {
          range: '${label} must be between ${min} and ${max}',
        },
      },
    };
    this.setVisible = this.setVisible.bind(this);
    this.onPanelChange = this.onPanelChange.bind(this);
    this.disabledDate = this.disabledDate.bind(this);
    this.getClassName = this.getClassName.bind(this);
    this.dateCellRender = this.dateCellRender.bind(this);
  }
  async componentWillMount (){
    this.getDate()
  }
  getDate=async ()=>{
    const  selectList = await Http.get('/tour/banner/selectList',{page:1,pageSize:20})
    console.log('分页查询下拉选框数据',selectList)
    const  res = await Http.get('/tour/banner/getdaysList',{name:'myWorkDays'})
    console.log('res',res)
    this.setState({
      selectedList:res.data.split(','),
      alldays:this.getdiffdate(yearNow+'/0'+1+'/0'+1,yearNow+'/'+12+'/'+31)
    })
  }
  componentDidMount() {
    window.addEventListener("resize", () => {
      this.setState({
        height: window.innerHeight - 108,
      });
    });
  }
  setVisible(flag) {
    console.log('参数',this.state.selectedList)
    // if(this.state.selectedList.length>0){
    //   let data={
    //     name:'myWorkDays',
    //     value:this.state.selectedList.join(',')
    //   }
    //  let res = Http.post('/tour/banner/add',data)
    //  console.log('774364646',res)
    // }
    this.setState({
      visible: flag,
    });
  }

  getThisMonthDays(d) {
    if (d) {
      var year = d.split("-")[0];
      var month = d.split("-")[1];
      var day = new Date(year, month, 0);
      return day.getDate();
    }
  }
  onPanelChange(value, mode) {
    console.log(value, mode);
  }
  getClassName(date) {
    return this.state.selectedList.includes(date);
  }
  disabledDate(current) {
    var days = this.getThisMonthDays(current._i);
    let date =
      current.year() +
      "/" +
      (current.month() + 1 > 9
        ? current.month() + 1
        : "0" + (current.month() + 1)) +
      "/" +
      (current.date() > 9 ? current.date() : "0" + current.date());
    let firstDaytempStr = new Date(
      current._i.split("-")[0] + "/" + current._i.split("-")[1] + "/" + days
    ).getTime(); // 月份最后天时间戳
    let lastDaytempStr = new Date(
      current._i.split("-")[0] + "/" + current._i.split("-")[1] + "/" + 1
    ).getTime(); // 月份第一天时间戳
    let todaytempStr = new Date(date);
    return firstDaytempStr < todaytempStr || todaytempStr < lastDaytempStr;
  }
  dateCellRender(d) {
    console.log(d)
    // 加进单元格
    let day = d.date() > 9 ? d.date() : "0" + d.date();
    let date =
      d.year() +
      "-" +
      (d.month() + 1 > 9 ? d.month() + 1 : "0" + (d.month() + 1)) +
      "-" +
      (d.date() > 9 ? d.date() : "0" + d.date());
    return this.getClassName(date) &&
      d._i == d.year() + "-" + (d.month() + 1) ? (
      <div className="selectedDate">{day}</div>
    ) : null;
  }
 getMonthBetween(start,end){  
    var result = [];  
    var s = start.split("-");  
    var e = end.split("-");  
    var min = new Date();  
    var max = new Date();  
    min.setFullYear(s[0],s[1]);  
    max.setFullYear(e[0],e[1]);  
      console.log(e[0]+"---- "+e[1]);
    var curr = min;  
    while(curr <= max){  
        var month = curr.getMonth();  
        //month=month==0?12:month;
        console.log(month);
        var str=curr.getFullYear()+"-"+(month);
        var s=curr.getFullYear()+"-0";
        if(str==s){
          str=curr.getFullYear()+"-12";
        }
        result.push(str);  
        curr.setMonth(month+1);
    } 
    // let newStr=[]
    // result.map(item=>{
    //   console.log(item)
    //   // let str =(item.split('-')[0]+'-'+(+item.split('-')[1]>9?item.split('-')[1]:'0'+item.split('-')[1]))
    //   let str =(item.split('-')[0]+'-'+(+item.split('-')[1]>9?item.split('-')[1]:'0'+item.split('-')[1]))
    //   newStr.push(str)
    //   // newStr.push(str)
    // })
    return result;  
   }
   //获取两日期之间日期列表函数
 getdiffdate(stime,etime){
   console.log('stime',stime)
   console.log('etime',etime)
  //初始化日期列表，数组
  var diffdate = new Array();
  var i=0;
  //开始日期小于等于结束日期,并循环
  while(stime<=etime){
      // diffdate[i] = stime.replace(/\//g,'-');
      diffdate[i] = stime.replace(/\//g,'-');
      //获取开始日期时间戳
      var stime_ts = new Date(stime).getTime();
      // console.log('当前日期：'+stime   +'当前时间戳：'+stime_ts);
      
      //增加一天时间戳后的日期
      var next_date = stime_ts + (24*60*60*1000);
      
      //拼接年月日，这里的月份会返回（0-11），所以要+1
      var next_dates_y = new Date(next_date).getFullYear()+'-';
      var next_dates_m = (new Date(next_date).getMonth()+1 < 10)?'0'+(new Date(next_date).getMonth()+1)+'-':(new Date(next_date).getMonth()+1)+'-';
      var next_dates_d = (new Date(next_date).getDate() < 10)?'0'+new Date(next_date).getDate():new Date(next_date).getDate();

      stime = next_dates_y+next_dates_m+next_dates_d;
      
      //增加数组key
      i++;
  }
  return diffdate
}
transferToWorkingDay=async()=>{
  const {selectedList}=this.state
  let data={
    name:'myWorkDays',
    value:selectedList.join(',')
  }
 let res =await Http.post('/tour/banner/add',data)
 if(res.code == 200){
   message.success('转换成功！')
   this.getDate()
 }
}
getUnWorkingDays=(value)=>{
  const {selectedList}=this.state
  let flag=true
  selectedList.map(item=>{
    if(item == value){
      flag =false
    }
  })
  return flag
}
handleCustomSelectValue=(v)=>{
  console.log(v)
}
transferToUnWorkingDay= async()=>{
  const {alldays}=this.state
  let tempArr=[]
  alldays.map(item=>{
    if(this.getUnWorkingDays(item)){
      tempArr.push(item)
    }
  })
  let data={
    name:'myWorkDays',
    value:tempArr.join(',')
  }
 let res = await Http.post('/tour/banner/add',data)
 console.log('22',res)
 if(res.code == 200){
   message.success('转换成功！')
   this.getDate()
 }
}
onSelect=(data)=>{
  const {selectedList} =this.state
  console.log(selectedList)
    const selectDay = moment(data._d).format('YYYY-MM-DD')
    console.log(selectDay)
    if(this.state.selectedList.indexOf(selectDay) === -1){
      this.setState({
        selectedList:[...this.state.selectedList,selectDay]
      },()=>{
        this.render()
      })
    }else{
      this.setState({
        selectedList:this.removeThisItem(selectDay)
      },()=>{
        this.render()
      })
    }
    
};
removeThisItem=(value)=>{
     let resArr=[];
     this.state.selectedList.map(item=>{
       if(item != value){
         resArr.push(item)
       }
     })
     return resArr
}
async  onFinish(values) {
    console.log(values)
    const data = {
      name:values.user.name
    }
   let res =  await Http.post('/tour/banner/selectAdd',data)
   console.log(res)
   if(res.code == 200){
    message.success('添加成功！')
   }else{
     message.error(res.message)
   }
};
getModalHeader(){
    const {Mounths1} =this.state
    return <Toolsbox><RangePicker  locale={locale} onChange={e=>{
      if(e){
        const start = e[0]._d.getFullYear()+'-'+ (e[0]._d.getMonth() +1)
        const end = e[1]._d.getFullYear()+'-'+ (e[1]._d.getMonth() +1)
        const res =  this.getMonthBetween(start,end)
        var s = res[0]+'-01'
        var e = res[res.length-1] +"-"+this.getThisMonthDays(res[res.length-1])
        console.log(999999,s)
        const alldays = this.getdiffdate(s,e)
        console.log(alldays)
        this.setState({
          Mounths:res,
          alldays
        })
      }else{
        this.setState({
          Mounths:Mounths1,
          alldays:this.getdiffdate(yearNow+'/0'+1+'/0'+1,yearNow+'/'+12+'/'+31)
        })
      }
    }}/> <Button type="primary" onClick={this.transferToWorkingDay}>转工作日</Button><Button type="primary" onClick={this.transferToUnWorkingDay}>转非工作日</Button></Toolsbox> 
  }
  beforeUpload =(file) =>{
    let type =file.name.substring(file.name.lastIndexOf("."))
    let passType=['.xlsx','.xls']
    if(passType.includes(type)){
      // 允许导入
    }else{
      message.error('不接受此文件类型！')
    }
  }
  render() {
    const { Mounths, height, visible ,arr,} = this.state;
    console.log(Mounths)
    return (
      <div className="buttoncontainer">
        <Button type="primary" onClick={() => this.setVisible(true)}>
          Open Modal of 1000px width
        </Button>
        <CustomSelect
          dataSource={arr}
          showSearch
          url={'/tour/banner/selectList'}
          pagesize={10}
          placeholder="Custom select"
          style={{ width: 180 }}
          onChange={this.handleCustomSelectValue}
        />
          <Upload 
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76" 
          name={'file'} 
          showUploadList={false}
          action={(file)=>{
            console.log(file)
            this.setState({
              file:file.name
            })
          }} previewFile={(file)=>{
            console.log(file)
          }}
          beforeUpload={this.beforeUpload}
          >
            <Button>Click to Upload</Button>
        </Upload>
        <UploadFile></UploadFile>
        <Modal
          title={this.getModalHeader()}
          centered={true}
          visible={visible}
          onOk={() => this.setVisible(false)}
          onCancel={() => this.setVisible(false)}
          width={1200}
          bodyStyle={{
            maxHeight: height + "px",
            overflow: "auto",
          }}
        >
          <div style={calendarContainer}>
            {Mounths.map((item) => {
              let nValue = moment(item);
              return (
                <div style={container} key={item}>
                  <Calendar
                    locale={locale}
                    fullscreen={false}
                    onPanelChange={this.onPanelChange}
                    headerRender={({ value, type, onChange, onTypeChange }) => {
                      var date = item.split('-')[0] + "年" + item.split('-')[1] + "月";
                      onChange = (data) => {
                        return false;
                        console.log("data", data);
                      };
                      onTypeChange = (tdata) => {
                        console.log("tdata", tdata);
                      };
                      return <CalendarHeader date={date}>  </CalendarHeader>;
                    }}
                    value={nValue}
                    dateCellRender={this.dateCellRender}
                    disabledDate={this.disabledDate}
                    onSelect={this.onSelect}
                  />
                </div>
              );
            })}
          </div>
        </Modal>
        <Form {...layout} name="nest-messages" onFinish={this.onFinish} validateMessages={this.state.validateMessages}>
      <Form.Item name={['user', 'name']} label="Name" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
      </div>
    );
  }
}
export default List;
